package com.geo.auth.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.geo.auth.entity.UserRole;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;

import java.util.List;

/**
 * 用户角色关联Mapper接口
 */
@Mapper
public interface UserRoleMapper extends BaseMapper<UserRole> {
    
    /**
     * 根据用户ID查询用户角色关联
     */
    @Select("SELECT * FROM user_roles WHERE user_id = #{userId} AND deleted = 0")
    List<UserRole> findByUserId(@Param("userId") String userId);
    
    /**
     * 根据角色ID查询用户角色关联
     */
    @Select("SELECT * FROM user_roles WHERE role_id = #{roleId} AND deleted = 0")
    List<UserRole> findByRoleId(@Param("roleId") String roleId);
    
    /**
     * 查询用户是否拥有指定角色
     */
    @Select("SELECT COUNT(*) FROM user_roles WHERE user_id = #{userId} AND role_id = #{roleId} AND deleted = 0")
    int countByUserIdAndRoleId(@Param("userId") String userId, @Param("roleId") String roleId);
    
    /**
     * 删除用户的所有角色
     */
    @Delete("UPDATE user_roles SET deleted = 1, updated_at = NOW() WHERE user_id = #{userId}")
    int deleteByUserId(@Param("userId") String userId);
    
    /**
     * 删除指定用户的指定角色
     */
    @Delete("UPDATE user_roles SET deleted = 1, updated_at = NOW() WHERE user_id = #{userId} AND role_id = #{roleId}")
    int deleteByUserIdAndRoleId(@Param("userId") String userId, @Param("roleId") String roleId);
    
    /**
     * 批量插入用户角色关联
     */
    @Insert("<script>" +
            "INSERT INTO user_roles (id, user_id, role_id, created_at, updated_at) VALUES " +
            "<foreach collection='userRoles' item='item' separator=','>" +
            "(#{item.id}, #{item.userId}, #{item.roleId}, #{item.createdAt}, #{item.updatedAt})" +
            "</foreach>" +
            "</script>")
    int batchInsert(@Param("userRoles") List<UserRole> userRoles);
    
    /**
     * 根据角色代码查询拥有该角色的用户ID列表
     */
    @Select("SELECT ur.user_id FROM user_roles ur " +
            "INNER JOIN roles r ON ur.role_id = r.id " +
            "WHERE r.role_code = #{roleCode} AND ur.deleted = 0 AND r.deleted = 0")
    List<String> findUserIdsByRoleCode(@Param("roleCode") String roleCode);
}